#pragma once

#include <iostream>
#include <cerrno>
#include <cstring>
#include <strings.h>
#include <functional>
#include <cstdlib>
#include <unordered_map>
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unordered_map>
#include "err.hpp"
#include "Ringqueue.hpp"
#include "LockGuard.hpp"
#include "Thread.hpp"

namespace Alpaca
{
    const static uint16_t default_port = 8080;
    using func_t = std::function<std::string(std::string)>;

    class UdpServer
    {
    public:
        UdpServer(uint16_t port = default_port) : _port(port)
        {
            pthread_mutex_init(&_lock, nullptr);
            p = new Thread(1, std::bind(&UdpServer::Recv, this));
            c = new Thread(2, std::bind(&UdpServer::Broadcast, this));
        }

        ~UdpServer()
        {
            pthread_mutex_destroy(&_lock);
            c->join();
            p->join();

            delete c;
            delete p;
        }

        void start()
        {
            // 创建套接字接口->打开网络文件
            _sock = socket(AF_INET, SOCK_DGRAM, 0);
            if (_sock < 0)
            {
                std::cerr << "creat socket error " << strerror(errno) << std::endl;
                exit(SOCKET_ERR);
            }
            std::cout << "creat socket success " << _sock << std::endl;

            // 给服务器指明IP和Port
            struct sockaddr_in local;
            bzero(&local, sizeof(local));
            local.sin_family = AF_INET; // 标志网络通信
            local.sin_port = htons(_port);
            // udp_server启动的时候bind本主机的任意一个IP
            local.sin_addr.s_addr = INADDR_ANY;

            if (bind(_sock, (sockaddr *)&local, sizeof(local)) < 0)
            {
                std::cerr << "bind socket error " << strerror(errno) << std::endl;
                exit(BIND_ERR);
            }
            std::cout << "bind socket success " << _sock << std::endl;

            p->run();
            c->run();
        }

        void addUser(std::string &name, sockaddr_in &peer)
        {
            LockGuard lockguard(&_lock);
            onlineuser[name] = peer;
            std::cout << "add uesr success" << std::endl;
        }

        void Recv() // 接收
        {
            std::cout << "start recv" << std::endl;
            char buffer[1024];
            while (true)
            {
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                // 收
                int n = recvfrom(_sock, buffer, sizeof(buffer) - 1, 0, (sockaddr *)&peer, &len);
                if (n > 0)
                    buffer[n] = '\0';
                else
                    continue;
                std::cout << "recv done ..." << std::endl;
                std::string clientip = inet_ntoa(peer.sin_addr);
                uint16_t clientport = ntohs(peer.sin_port);
                std::cout << clientip << "-" << clientport << "# "
                << "get message# " << buffer << std::endl;

                // 构建一个用户，并检查
                std::string name = clientip;
                name += "-";
                name += std::to_string(clientport);
                addUser(name, peer); // 不存在就插入，存在则不进行操作
                std::string message = name + ">> " + buffer;
                rq.push(message);
                // // 进行业务处理
                // std::string message = _service(buffer);
            }
        }

        void Broadcast() // 广播
        {
            while (true)
            {
                std::string sendstring;
                rq.pop(&sendstring);
                std::vector<sockaddr_in> v;
                {
                    LockGuard lockguard(&_lock);
                    for (auto &usr : onlineuser)
                    {
                        v.push_back(usr.second);
                    }
                }
                for (auto &usr : v)
                {
                    // std::cout << "Broadcast message to " << usr.first << std::endl;
                    sendto(_sock, sendstring.c_str(), sendstring.size(), 0, (sockaddr *)&usr, sizeof(usr));
                }
            }
        }

    private:
        int _sock;
        uint16_t _port;
        // func_t _service;
        pthread_mutex_t _lock;
        std::unordered_map<std::string, sockaddr_in> onlineuser;
        RingQueue<std::string> rq;
        Thread *c;
        Thread *p;
        // std::string _ip;
    };
}